﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ConsoleTest.Tools
{
    public static class Utils
    {
        // 对象序列化成json字符串
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        //反序列化成对象
        public static T ToObject<T>(this string obj)
        {
            return JsonConvert.DeserializeObject<T>(obj);
        }

        /// <summary>  
        /// 将Dictionary序列化为json数据  
        /// </summary>  
        /// <param name="jsonData">json数据</param>  
        /// <returns></returns>  
        public static string DictionaryToJson(Dictionary<int, object> dic)
        {
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象  
                return JsonConvert.SerializeObject(dic);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        ///   //地址编码 gbk
        /// </summary>
        /// <param name="dataStr"></param>
        /// <returns></returns>
        public static string UrlEncode(string dataStr, string codeType)
        {
            return HttpUtility.UrlEncode(dataStr, Encoding.GetEncoding(codeType));
        }

        /// <summary>
        ///  //地址解码 gbk
        /// </summary>
        /// <param name="dataStr"></param>
        /// <returns></returns>
        public static string UrlDecode(string dataStr, string codeType)
        {
            return HttpUtility.UrlDecode(dataStr, Encoding.GetEncoding(codeType));
        }

       
    }
}
